from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.db.models import Q
from datetime import datetime, timedelta

from .models import (
    EvaluationAnalysis, 
    ImprovementSuggestion, 
    TrainingRecommendation, 
    DriverImprovementMemory
)
from .serializers import (
    EvaluationAnalysisSerializer,
    ImprovementSuggestionSerializer,
    TrainingRecommendationSerializer,
    DriverImprovementMemorySerializer
)
from .evaluation_service import EvaluationAnalysisService
from .memory_service import DriverMemoryService

# Create your views here.

class EvaluationAnalysisView(APIView):
    """评价分析视图"""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.evaluation_service = EvaluationAnalysisService()
    
    def post(self, request):
        """分析单个评价"""
        order_rating_id = request.data.get('order_rating_id')
        
        if not order_rating_id:
            return Response(
                {'error': '缺少order_rating_id参数'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            # 首先检查评价是否存在
            from order.models import OrderRating
            try:
                rating = OrderRating.objects.get(id=order_rating_id)
                # 返回评价基本信息用于调试
                rating_info = {
                    'id': rating.id,
                    'order_id': rating.order.id if rating.order else None,
                    'passenger_id': rating.passenger_id,
                    'driver_id': rating.driver_id,
                    'rating': rating.rating,
                    'comment': rating.comment,
                    'rating_time': rating.rating_time
                }
            except OrderRating.DoesNotExist:
                return Response({
                    'error': f'订单评价ID {order_rating_id} 不存在',
                    'suggestion': '请先创建评价数据或检查ID是否正确'
                }, status=status.HTTP_404_NOT_FOUND)
            
            # 执行分析
            result = self.evaluation_service.analyze_evaluation(order_rating_id)
            
            # 添加评价信息到结果中
            result['rating_info'] = rating_info
            
            if result.get('success'):
                return Response(result, status=status.HTTP_200_OK)
            else:
                return Response(result, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                
        except Exception as e:
            return Response({
                'error': str(e),
                'rating_id': order_rating_id
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def get(self, request):
        """获取评价分析列表"""
        driver_id = request.query_params.get('driver_id')
        rating = request.query_params.get('rating')  # 评分范围
        start_date = request.query_params.get('start_date')  # 开始日期
        end_date = request.query_params.get('end_date')  # 结束日期
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 20))
        
        query = EvaluationAnalysis.objects.all()
        
        # 司机ID筛选
        if driver_id:
            query = query.filter(order_rating__driver_id=driver_id)
        
        # 评分范围筛选
        if rating:
            query = query.filter(order_rating__rating=rating)
        
        # 评分范围筛选（支持范围查询）
        rating_min = request.query_params.get('rating_min')
        rating_max = request.query_params.get('rating_max')
        if rating_min and rating_max:
            query = query.filter(order_rating__rating__range=[int(rating_min), int(rating_max)])
        elif rating_min:
            query = query.filter(order_rating__rating__gte=int(rating_min))
        elif rating_max:
            query = query.filter(order_rating__rating__lte=int(rating_max))
        
        # 时间范围筛选
        if start_date and end_date:
            query = query.filter(analysis_time__date__range=[start_date, end_date])
        elif start_date:
            query = query.filter(analysis_time__date__gte=start_date)
        elif end_date:
            query = query.filter(analysis_time__date__lte=end_date)
        
        # 分页
        start = (page - 1) * page_size
        end = start + page_size
        analyses = query.order_by('-analysis_time')[start:end]
        
        serializer = EvaluationAnalysisSerializer(analyses, many=True)
        
        return Response({
            'data': serializer.data,
            'page': page,
            'page_size': page_size,
            'total': query.count()
        })

class BatchAnalysisView(APIView):
    """批量分析视图"""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.evaluation_service = EvaluationAnalysisService()
    
    def post(self, request):
        """批量分析评价"""
        driver_id = request.data.get('driver_id')
        limit = int(request.data.get('limit', 10))
        
        try:
            result = self.evaluation_service.batch_analyze_evaluations(driver_id, limit)
            
            if result.get('success') is not False:
                return Response(result, status=status.HTTP_200_OK)
            else:
                return Response(result, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class ImprovementSuggestionView(APIView):
    """改进建议视图"""
    
    def get(self, request):
        """获取改进建议列表"""
        driver_id = request.query_params.get('driver_id')
        suggestion_type = request.query_params.get('suggestion_type')
        priority = request.query_params.get('priority')
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 20))
        
        print(f"=== 改进建议API调用 ===")
        print(f"参数: driver_id={driver_id}, suggestion_type={suggestion_type}, priority={priority}")
        print(f"分页: page={page}, page_size={page_size}")
        
        query = ImprovementSuggestion.objects.all()
        
        if driver_id:
            query = query.filter(analysis__order_rating__driver_id=driver_id)
        
        if suggestion_type:
            query = query.filter(suggestion_type=suggestion_type)
        
        if priority:
            query = query.filter(priority=priority)
        
        # 分页
        start = (page - 1) * page_size
        end = start + page_size
        suggestions = query.order_by('-generated_time')[start:end]
        
        print(f"查询结果数量: {suggestions.count()}")
        for suggestion in suggestions:
            print(f"建议ID: {suggestion.id}, 类型: {suggestion.suggestion_type}, 内容长度: {len(suggestion.suggestion_content)}")
        
        serializer = ImprovementSuggestionSerializer(suggestions, many=True)
        
        response_data = {
            'data': serializer.data,
            'page': page,
            'page_size': page_size,
            'total': query.count()
        }
        
        print(f"返回数据: {response_data}")
        return Response(response_data)

class TrainingRecommendationView(APIView):
    """培训建议视图"""
    
    def get(self, request):
        """获取培训建议列表"""
        driver_id = request.query_params.get('driver_id')
        status_filter = request.query_params.get('status')
        priority = request.query_params.get('priority')
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 20))
        
        query = TrainingRecommendation.objects.all()
        
        if driver_id:
            query = query.filter(driver_id=driver_id)
        
        if status_filter is not None:
            query = query.filter(status=status_filter)
        
        if priority:
            query = query.filter(priority=priority)
        
        # 分页
        start = (page - 1) * page_size
        end = start + page_size
        recommendations = query.order_by('-created_time')[start:end]
        
        serializer = TrainingRecommendationSerializer(recommendations, many=True)
        
        return Response({
            'data': serializer.data,
            'page': page,
            'page_size': page_size,
            'total': query.count()
        })
    
    def post(self, request):
        """推送培训建议"""
        recommendation_id = request.data.get('recommendation_id')
        
        if not recommendation_id:
            return Response(
                {'error': '缺少recommendation_id参数'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            recommendation = TrainingRecommendation.objects.get(id=recommendation_id)
            recommendation.status = 1  # 已推送
            recommendation.pushed_time = datetime.now()
            recommendation.save()
            
            return Response({
                'message': '培训建议推送成功',
                'recommendation_id': recommendation_id
            })
            
        except TrainingRecommendation.DoesNotExist:
            return Response(
                {'error': '培训建议不存在'}, 
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    def put(self, request):
        """更新培训建议状态"""
        recommendation_id = request.data.get('recommendation_id')
        new_status = request.data.get('status')
        
        if not recommendation_id or new_status is None:
            return Response(
                {'error': '缺少recommendation_id或status参数'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            recommendation = TrainingRecommendation.objects.get(id=recommendation_id)
            recommendation.status = new_status
            recommendation.save()
            
            return Response({
                'message': '状态更新成功',
                'recommendation_id': recommendation_id,
                'new_status': new_status
            })
            
        except TrainingRecommendation.DoesNotExist:
            return Response(
                {'error': '培训建议不存在'}, 
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class DriverProfileView(APIView):
    """司机档案视图"""
    
    def get(self, request):
        """获取司机改进档案"""
        driver_id = request.query_params.get('driver_id')
        
        if not driver_id:
            return Response(
                {'error': '缺少driver_id参数'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            memory_service = DriverMemoryService(int(driver_id))
            profile = memory_service.get_driver_profile()
            
            return Response(profile)
            
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class DriverMemoryView(APIView):
    """司机记忆视图"""
    
    def get(self, request):
        """获取司机记忆"""
        driver_id = request.query_params.get('driver_id')
        memory_type = request.query_params.get('memory_type')
        memory_key = request.query_params.get('memory_key')
        
        if not driver_id:
            return Response(
                {'error': '缺少driver_id参数'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            memory_service = DriverMemoryService(int(driver_id))
            
            if memory_key:
                # 获取特定记忆
                memory_value = memory_service.retrieve_memory(memory_type, memory_key)
                return Response({'memory_value': memory_value})
            else:
                # 获取类型记忆列表
                memories = memory_service.retrieve_memories_by_type(memory_type or 'rating_history')
                return Response({'memories': memories})
                
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    def post(self, request):
        """存储司机记忆"""
        driver_id = request.data.get('driver_id')
        memory_type = request.data.get('memory_type')
        memory_key = request.data.get('memory_key')
        memory_value = request.data.get('memory_value')
        importance_score = request.data.get('importance_score', 1.0)
        
        if not all([driver_id, memory_type, memory_key, memory_value]):
            return Response(
                {'error': '缺少必要参数'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            memory_service = DriverMemoryService(int(driver_id))
            success = memory_service.store_memory(
                memory_type, 
                memory_key, 
                memory_value, 
                importance_score
            )
            
            if success:
                return Response({'message': '记忆存储成功'})
            else:
                return Response(
                    {'error': '记忆存储失败'}, 
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
                
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class EvaluationDashboardView(APIView):
    """评价分析仪表板视图"""
    
    def get(self, request):
        """获取评价分析统计信息"""
        driver_id = request.query_params.get('driver_id')
        days = int(request.query_params.get('days', 30))
        
        # 添加可用评价数据查询
        show_available_ratings = request.query_params.get('show_available', 'false').lower() == 'true'
        
        if show_available_ratings:
            return self._get_available_ratings(request, driver_id)
        
        try:
            # 计算时间范围
            end_date = datetime.now()
            start_date = end_date - timedelta(days=days)
            
            # 基础查询
            analysis_query = EvaluationAnalysis.objects.filter(
                analysis_time__range=(start_date, end_date)
            )
            
            if driver_id:
                analysis_query = analysis_query.filter(order_rating__driver_id=driver_id)
            
            # 统计信息
            total_analyses = analysis_query.count()
            
            # 情感分析统计
            sentiment_stats = {
                'positive': analysis_query.filter(sentiment_label='正面').count(),
                'negative': analysis_query.filter(sentiment_label='负面').count(),
                'neutral': analysis_query.filter(sentiment_label='中性').count(),
            }
            
            # 平均情感得分
            from django.db import models
            avg_sentiment = analysis_query.aggregate(
                avg_score=models.Avg('sentiment_score')
            )['avg_score'] or 0
            
            # 改进建议统计
            suggestion_query = ImprovementSuggestion.objects.filter(
                analysis__in=analysis_query
            )
            
            suggestion_stats = {
                'total': suggestion_query.count(),
                'high_priority': suggestion_query.filter(priority=1).count(),
                'medium_priority': suggestion_query.filter(priority=2).count(),
                'low_priority': suggestion_query.filter(priority=3).count(),
            }
            
            # 培训建议统计
            if driver_id:
                training_query = TrainingRecommendation.objects.filter(
                    driver_id=driver_id,
                    created_time__range=(start_date, end_date)
                )
            else:
                training_query = TrainingRecommendation.objects.filter(
                    created_time__range=(start_date, end_date)
                )
            
            training_stats = {
                'total': training_query.count(),
                'pending': training_query.filter(status=0).count(),
                'pushed': training_query.filter(status=1).count(),
                'viewed': training_query.filter(status=2).count(),
                'completed': training_query.filter(status=3).count(),
            }
            
            # 获取总评价数
            from order.models import OrderRating
            total_ratings_query = OrderRating.objects.all()
            if driver_id:
                total_ratings_query = total_ratings_query.filter(driver_id=driver_id)
            total_ratings = total_ratings_query.count()
            
            return Response({
                'period': f'最近{days}天',
                'total_ratings': total_ratings,
                'analyzed_ratings': total_analyses,
                'improvement_suggestions': suggestion_stats['total'],
                'training_recommendations': training_stats['total'],
                'total_analyses': total_analyses,
                'sentiment_stats': sentiment_stats,
                'avg_sentiment_score': round(avg_sentiment, 2),
                'suggestion_stats': suggestion_stats,
                'training_stats': training_stats,
            })
            
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    def _get_available_ratings(self, request, driver_id):
        """获取可用的评价数据"""
        try:
            from order.models import OrderRating
            
            # 查询所有评价
            query = OrderRating.objects.all()
            if driver_id:
                query = query.filter(driver_id=driver_id)
            
            # 分页
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('page_size', 10))
            start = (page - 1) * page_size
            end = start + page_size
            
            ratings = query.order_by('-rating_time')[start:end]
            
            # 检查哪些评价已经分析过
            rating_data = []
            for rating in ratings:
                has_analysis = EvaluationAnalysis.objects.filter(order_rating=rating).exists()
                analysis = EvaluationAnalysis.objects.filter(order_rating=rating).first()
                rating_data.append({
                    'id': rating.id,
                    'order_id': rating.order.id if rating.order else None,
                    'passenger_id': rating.passenger_id,
                    'driver_id': rating.driver_id,
                    'rating': rating.rating,
                    'comment': rating.comment,
                    'rating_time': rating.rating_time,
                    'has_analysis': has_analysis,
                    'analysis_id': analysis.id if analysis else None
                })
            
            return Response({
                'data': rating_data,
                'page': page,
                'page_size': page_size,
                'total': query.count(),
                'message': '使用 show_available=true 参数查看可用的评价数据'
            })
            
        except Exception as e:
            return Response(
                {'error': str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
